package com.atguigu.ucenterservice.controller;

import com.atguigu.commonutils.jwt.JwtUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.ucenterservice.entity.UcenterMember;
import com.atguigu.ucenterservice.service.UcenterMemberService;
import com.atguigu.ucenterservice.utlis.ConstantPropertiesUtil;
import com.atguigu.ucenterservice.utlis.HttpClientUtils;
import com.google.gson.Gson;
import com.sun.deploy.net.URLEncoder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;


@Api(tags = "微信登陆相关接口")
@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    @ApiOperation("获取二维码")
    @GetMapping("getcode")
    public String getCode(){
        //1.模板url（未填充参数）
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=atguigu" +
                "#wechat_redirect";

        //2.对回调url进行编码处理
        String redirectUrl= ConstantPropertiesUtil.REDIRECT_URL;
        try {
            redirectUrl= URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new GuliException(20001,"服务器出错了");
        }

        //3.填充模板url参数
        String qrcodeUrl=String.format(baseUrl,ConstantPropertiesUtil.APP_ID,redirectUrl);

        //4.重定向到该url
        return "redirect:"+qrcodeUrl;
    }

    @ApiOperation("扫码后回调地址")
    @GetMapping("callback")
    public String callBack(String code, String state){
        //1.用code和secret,appid去换取accessToken
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantPropertiesUtil.APP_ID,
                ConstantPropertiesUtil.APP_SECRET,
                code);
        String res=null;
        try {
            res = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "换取token出错");
        }
        System.out.println("res:"+res);

        //2.把已经获取的token封装进map中,并从accessTokenInfo取出accessToken，openid获取用户信息
        Gson gson = new Gson();
        HashMap accessTokenInfo = gson.fromJson(res, HashMap.class);
        String accessToken = (String) accessTokenInfo.get("access_token");
        String openId = (String) accessTokenInfo.get("openid");

        //3.根据openid查询数据库，看是否已经注册过的
        UcenterMember member=memberService.getByOpenId(openId);

        if (member==null){
            //没注册：进行获取信息并注册
            System.out.println("新用户注册");

            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openId);
            String userInfo = null;
            try {
                userInfo=HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo"+userInfo);
            } catch (Exception e) {
                e.printStackTrace();
                throw new GuliException(20001, "获取用户信息出错");
            }
            //封装进menber对象并存入数据库
            HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
            System.out.println("userInfoMap"+userInfoMap);
            member=new UcenterMember();
            member.setNickname((String) userInfoMap.get("nickname"));
            member.setOpenid((String) userInfoMap.get("openid"));
            member.setAvatar((String) userInfoMap.get("headimgurl"));
            memberService.save(member);
        }

        //根据id和昵称生成jwt令牌并返回
        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        return "redirect:"+"http://localhost:3000?token="+token;
    }
}
